var module="../project_weather";
var sub="weather";
/*================================================================================*/
jQuery(document).ready(function() {
	Page.init();
});
/* ================================================================================ */
//关于页面的控件生成等操作都放在Page里
var Page = function() {
	/*----------------------------------------入口函数  开始----------------------------------------*/
	var initPageControl=function(){
		pageId=$("#page_id").val();
		if(pageId=="weather_information_list"){
			initWeatherInfList();
		}
		if(pageId=="device_add"){
			initWeaterAdd();
		}
		if(pageId=="Weather_modify"){
			initWeatherModify();
		}
		if(pageId=="print_weather_information_table"){
			initPrintTabelRecord();
		}
		if(pageId=="file_information_statistic"){
			initStatisticOperation();
		}
		if(pageId=="upload_file_attachment"){
			initUploadWeather();
		}
	};
	/*----------------------------------------入口函数  结束----------------------------------------*/
	var columnsData=undefined;
	var recordResult=undefined;
	var modify_file_update=undefined;
	var chartData=[
		// {year: '2006', income: 100, expenses: 90},
		// {year: '2007', income: 75, expenses: 65},
		// {year: '2008', income: 50, expenses: 40},
		];
	// 天气首页的圆形图形的数据weather_graph_data
	var weather_graph_data=[
		{label: "最高气温", value: 12},
		{label: "最低气温", value: 30},
		{label: "风的等级", value: 1}
	];
	var user_role=sessionStorage.getItem('user_role'); // 通过全局session获取角色
	var user_id=sessionStorage.getItem('user_id');  // 通过全局session获取用户唯一id，可用于后续的权限管理

	var this_city=sessionStorage.getItem("update_city");
	var this_ganmao=sessionStorage.getItem("update_ganmao");
	var this_wendu=sessionStorage.getItem("update_wendu");


	/*----------------------------------------业务函数  开始----------------------------------------*/
	/*------------------------------针对各个页面的入口  开始------------------------------*/

	var initWeatherInfList=function(){
		initWeatherListControlEvent();
		initweather_information_tips(this_city,this_ganmao,this_wendu);
		initWeatherRecordList();
	};
	var initWeatherAdd=function(){
		initWeatherAddControlEvent();
	};
	var initWeatherModify=function(){
		initWeatherModifyControlEvent();
		initWeatherRecordView();
	};
	var initPrintTabelRecord=function(){
		initWeatherModifyControlEvent();
		initWeatherPrintTabelRecord();
	};
	var initStatisticOperation=function(){
		initStatisticPage();
	};
	var initWeatherStatistic=function(text){
		$.ajaxSettings.async = false;
		initWeatherStatisticRecord(text);
		$.ajaxSettings.async = true;
		initBarChart();
	};
	var initUploadWeather=function(){
		initUploadWeatherControlEvent();
		//initWeatherQueryRecord();
	};
	/*------------------------------针对各个页面的入口 结束------------------------------*/
	var getUrlParam=function(name){
		//获取url中的参数
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
		var r = window.location.search.substr(1).match(reg);  //匹配目标参数
		if (r != null) return decodeURI(r[2]); return null; //返回参数值，如果是中文传递，就用decodeURI解决乱码，否则用unescape
	};
	var initWeatherListControlEvent=function(){
		$("#help_button").click(function() {help();});
		$('#add_button').click(function() {onAddRecord();});
		$('#datatable_button').click(function() {onDataTableTab();});
		$('#export_button').click(function() {onExportRecord();});
		$('#print_tabel_button').click(function() {onPrintTabelRecord();});
		$('#statistic_tabel_button').click(function() {onStatisticRecord();});
		$('#add_submit_show').click(function() {onAddRecord();});
		$('#record_modify_div #submit_button').click(function() {onModifySubmit();});
		$('#record_add_div #add_submit_button').click(function() {onAddSubmit();});
		$('#record_add_div #add_input_file').click(function() {initUploadWeatherPage();});

	};
	var initWeatherAddControlEvent=function(){
		$("#help_button").click(function() {help();});
		$('#add_button').click(function() {submitAddRecord();});
	};
	var initWeatherModifyControlEvent=function(){
		$("#help_button").click(function() {help();});
		$('#modify_button').click(function() {submitModifyRecord();});
	};
	var onupdatefiledivshow=function(){
		var div = document.getElementById('choose_file_div');
		if ($("#check_file_update").is(":checked") == true) {
			alert("这个框被选中了！");
			div.style.display = "block";
		} else {
			alert("这个框没有被选中！");
			div.style.display = "none";
		}
	};
	var initUploadWeatherControlEvent=function(){
		$("#help_button").click(function() {help();});
		$("#upload_button").click(function() {initUploadWeatherPage();});
	};

	var initUploadWeatherControlEvent=function(){
		$("#help_button").click(function() {help();});
		$("#upload_button").click(function() {initUploadWeatherPage();});
	};


    // 前端页面的天气圆形图形
	var donut = new Morris.Donut({
		element: 'sales-chart',
		resize: true,
		colors: ["#3c8dbc", "#f56954", "#00a65a"],
		data: weather_graph_data,
		hideHover: 'auto'
	});


	var InsertWeatherDB=function (weatherData) {
		var data=weatherData;
		data.action="insert_weather_information_to_DB";
		console.log("构造插入的天气数据："+JSON.stringify(data));
		$.post(module+"_"+sub+"_servlet_action",data,function(json){
			console.log(JSON.stringify(json));
			if(json.result_code==0) {

			}
			else
			{
				alert("相关数据已经获取在数据库中了，无法再次同步到数据库！");
			}
		})
	}

	var GetweatherData=function (city) {
		var weatherdata={};
		var city=city;
		if(city==null) {
			city="成都";
		}
		$.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city, function(data) {
			var data = $.parseJSON(data).data;
			var weather = data.forecast;
			sessionStorage.setItem('update_city', data.city);
			sessionStorage.setItem('update_ganmao', data.ganmao);
			sessionStorage.setItem('update_wendu', data.wendu);
			console.log(data);
			changeResultDataToWeatherChartData(weather[0],weather_graph_data);
			for (var i = 0; i < weather.length; i++) {
				var originfengli = weather[i].fengli;
				var fengli = originfengli.substring(9, originfengli.length-3);
				var originmaxtemp = weather[i].high;
				var high = originmaxtemp.substring(3,originmaxtemp.length);
				var originmintemp = weather[i].high;
				var low = originmintemp.substring(3,originmintemp.length);
				console.log(fengli);
				weatherdata.location=city;
				weatherdata.date=weather[i].date;
				weatherdata.type=weather[i].type;
				weatherdata.fengxiang=weather[i].fengxiang;
				weatherdata.Maxtemperature=high;
				weatherdata.Mintemperature=low;
				weatherdata.fengli=fengli;
				InsertWeatherDB(weatherdata);
			}
			alert("已经将最新的天气数据存入了数据库！");
			window.location.reload();
		});
	}



	var initWeatherRecordView=function(){
		var id=getUrlParam("id");
		var data={};
		data.action="get_file_information_record";
		data.modify_user=user_id;
		data.id=id;
		$.post(module+"_"+sub+"_servlet_action",data,function(json){
			console.log(JSON.stringify(json));
			if(json.result_code==0){
				var list=json.aaData;
				if(list!=undefined && list.length>0){
					for(var i=0;i<list.length;i++){
						var record=list[i];
						$("#Weather_id").val(record.Weather_id);
						$("#Weather_name").val(record.Weather_name);
					}
				}
			}
		})
	};


	var initweather_information_tips=function (a,b,c) {
		var html="";
	html=html+"<div class=\"alert alert-danger alert-dismissable\">\n" +
		"\t\t\t<i class=\"fa fa-ban\"></i>\n" +
		"\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>\n" +
		"\t\t<b>Alert!</b> 你所在的城市是: " +a+
		"\t\t</div>";

	html=html+"<div class=\"alert alert-info alert-dismissable\">\n" +
		"\t\t\t<i class=\"fa fa-info\"></i>\n" +
		"\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>\n" +
		"\t\t<b>Alert!</b> 当前感冒易发指数：" +b+
		"\t\t</div>";


	html=html+"<div class=\"alert alert-warning alert-dismissable\">\n" +
			"\t\t\t<i class=\"fa fa-warning\"></i>\n" +
			"\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>\n" +
			"\t\t<b>Alert!</b> 目前温度是: " +c+" ℃"+
			"\t\t</div>";

		$("#Promote_message_div").html(html);
		console.log("构造的HTML是："+html);
	};

	var initWeatherPrintTabelRecord=function () {
		$.post(module+"_"+sub+"_servlet_action?action=get_weather_information_record",function(json){
			console.log(JSON.stringify(json));
			var html="";
			if(json.result_code==0){
				var list=json.aaData;
				if(list!=undefined && list.length>0){
					for(var i=0;i<list.length;i++){
						var record=list[i];
						html = html+"                        <tr>";

						html = html+"                        <td>";
						html = html+"                        <span class=\"badge bg-red\">"+(i+1);
						html = html+"                        </span>";
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.location;
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.date;
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.max_temperature;
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.min_temperature;
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.fengxiang;
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.fengli;
						html = html+"                        </td>";

						html = html+"                        <td>";
						html = html+"                         "+record.type;
						html = html+"                        </td>";

						html = html+"                        </tr>";

					}
				}
			}
			else{
				alert("[initWeatherPrintTabelRecord]前端与后端交互数据错误！");
			}
			$("#print_list_div").html(html);
		});
	};

	var initWeatherStatisticRecord=function(text){
		var data={};
		data.action="get_file_information_by_someType";
		data.group_by="type";
		data.order_by=text;
		$.post(module+"_"+sub+"_servlet_action",data,function(json){
			console.log(JSON.stringify(json));
			var html="";
			if(json.result_code==0){
				var list=json.aaData;
				if(list!=undefined && list.length>0){
						changeResultDataToChartData(list,chartData);
				}
				else {
					alert("[initWeatherStatisticRecord]前后端交互出错！"+json.result_msg);
				}
			}
		});
	};

	var onStatisticRecord=function(){
		window.location.href="file_information_statistic.html";
	};

	var onAddRecord=function(){
		$('#record_add_div').modal("show");
	};

	var submitModifyRecord=function(){
		if(confirm("您确定要修改该记录吗？")){
			var id=getUrlParam("id");
			var url=module+"_"+sub+"_servlet_action";
			var data={};
			data.action="modify_Weather_record";
			data.id=id;
			data.title=$("#title").val();
			data.modify_user=user_id;
			data.type=$("#type").val();
			$.post(url,data,function(json){
				if(json.result_code==0){
					alert("已经完成文件修改。");
					window.location.href="statistics.html";
				}
			});
		}
	};


	var initWeatherRecordList=function(){
		getWeatherRecordDatatable("get_weather_information_record");
		donut();
	};
	var initWeatherMobileRecord=function(){
		getWeatherMobileRecord();
	};

	var filerelativepath=null; // 定义指定文件相对路径的全局变量，这样方便调用
	var getWeatherPath = function(id){
		var url=module+"_"+sub+"_servlet_action";
		var data={};
		data.action="Get_Weather_Path";
		data.id=id;
		$.post(url,data,function(json){
			if(json.result_code==0){
				window.location.reload();
				filerelativepath=json.fileRelativePath;
			}
		});
	};

	var onDeleteRecord = function(id){
		if(confirm("您确定要删除这条记录吗？")){
			if(id>-1) {
				$.ajaxSettings.async = false;
				getWeatherPath(id);
				$.ajaxSettings.async = true;
					var url = module + "_" + sub + "_servlet_action";
					var data = {};
					data.action = "delete_Weather_record";
					data.id = id;
					data.fileRelativePath = filerelativepath;
					$.post(url, data, function (json) {
						if (json.result_code == 0) {
							if(json.result_msg=="ok") {
								alert("删除成功！");
							}
							else{
								alert("删除失败，请仔细检查原因！");
							}
							window.location.reload();
						}
					})
				}
			}
	};
	var onModifyRecord=function(id){
		for(var i=0;i<reslutList.length;i++) {
			if(id==reslutList[i].id) {
				$('#record_modify_div #id').val(reslutList[i].id);
				$('#record_modify_div #location').val(reslutList[i].location);
				$('#record_modify_div #max_temperature').val(reslutList[i].max_temperature);
				$('#record_modify_div #min_temperature').val(reslutList[i].min_temperature);
				$('#record_modify_div #type').val(reslutList[i].type);
				$('#record_modify_div').modal("show");
			}
		}
	};

	var onPrintTabelRecord=function(){
		window.location.href="printWeatherInfTabel.html";
	};

	var initStatisticPage=function(){
		var list = document.getElementById("Menu");
		var lis = list.getElementsByTagName("a");
        var text=null;
		list.addEventListener("click",function () {
			for (var i=0; i<lis.length; i++){
				lis[i].onclick = function (event) {
					text=this.innerText;
					alert(this.innerText);
					if(text!=null) {
						initWeatherStatistic(text);
					}
				}
			}
		});
	};

	var initUploadWeatherPage=function(){
		// 初始化文件上传的界面
		$("#download_url").html("");
		$("#attachment_id").html("");

		var filename = $("#input_file").val();
		var title=$("#file_name").val();
		var type=$("#file_type").val();
		var formData = new FormData();
		formData.append("files", $("#input_file")[0].files[0]);
		formData.append("file_type", $("#file_type").val());
		formData.append("file_name", $("#file_name").val());

		$.ajax({
			type: "POST",
			url: "../project_documents_file_servlet_action?action=upload_file_record",
			enctype: 'multipart/form-data',
			data: formData,
			dataType:"json",                //这一项必不可少
			contentType : false,            //这一项必不可少
			processData : false,            //这一项必不可少
			success: function (res) {
				alert("文件上传成功！");
				console.log(JSON.stringify(res));
				var downloadUrl=res.download_url;
				var attachmentId=res.attachment_id;
				var transfilename=null;
				var list=res.files;
				if(list!=undefined && list.length>0){
					transfilename=list[0].file_name;
				}
				alert("传上去了！download_url="+downloadUrl+"，attachment_id="+attachmentId+", transfilename="+transfilename);
				downloadUrl="../"+downloadUrl;
				$("#download_url").html("download_url="+downloadUrl);
				$("#attachment_id").html("attachment_id="+attachmentId);
				$("#download_link").attr("href",downloadUrl);
				$("#download_link").html("【点击下载】");

				//将后端为文件生成的流水号再次赋名，如20211123132712_786.pdf
				// 把中间的"_"替换为所属的type，到达见名知义的效果
				var standfilename =transfilename.replace(/(?<=_).*?.\w*/,type);
				alert("已为你标准化命名为"+standfilename);
				// 此时的standfilename就是最标准化的文件名，但是存储的文件还是没有规范命名，然而可以根据这个标识去查存储的文件，只需要前面相同

				submitAddRecord(title,type,attachmentId,standfilename);
			}
		});
	};

	var submitAddRecord=function(filename,type,attachment,standfilename){
		var url=module+"_"+sub+"_servlet_action";
		var data={};
		data.action="add_file_information_record";
		data.title=filename;
		data.type=type;
		data.create_user_id=user_id;
		data.create_user=user_role;
		data.attachment_ids=attachment;
		data.standard_file_name=standfilename;
		$.post(url,data,function(json){
			if(json.result_code==0){
				alert("已经同步到信息添加一栏！");
				window.location.reload();
			}
		});
	};


	var reslutList=[];
	var getWeatherRecordDatatable=function(action_value){
		reslutList=[];
		$('.datatable').dataTable({
			"autoWidth": true,
			"paging":true,
			"searching":true,
			"aaSorting": [], //不让其按第一列排序
			"oLanguage": {
				"aria": {
					"sortAscending": ": activate to sort column ascending",
					"sortDescending": ": activate to sort column descending"
				},
				"sProcessing":   "处理中...",
				"sLengthMenu":   "_MENU_ 记录/页",
				"sZeroRecords":  "没有匹配的记录",
				"sInfo":         "显示第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项",
				"sInfoEmpty":    "显示第 0 至 0 项记录，共 0 项",
				"sInfoFiltered": "(由 _MAX_ 项记录过滤)",
				"sInfoPostFix":  "",
				"sSearch":       "请输入查询信息:",
				"oPaginate": {
					"sFirst":    "首页",
					"sPrevious": "上页",
					"sNext":     "下页",
					"sLast":     "末页"
				}
			},
			"aoColumns": [{"mRender": function(data, type, full) {
					sReturn = '<input type="checkbox" class="checkboxes" value="'+full.id+'"/>';
					return sReturn;
				},"orderable": false
			},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.location+'</div>';
						return sReturn;
					},"orderable": false},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.date+'</div>';
						return sReturn;
					},"orderable": false},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.max_temperature+'</div>';
						return sReturn;
					},"orderable": false},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.min_temperature+'</div>';
						return sReturn;
					},"orderable": true},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.fengxiang+'</div>';
						return sReturn;
					},"orderable": false},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.fengli+'</div>';
						return sReturn;
					},"orderable": false},
				{"mRender": function(data, type, full) {
						sReturn = '<div>'+full.type+'</div>';
						return sReturn;
					},"orderable": false},
				{"mRender": function(data, type, full) {
					    reslutList.push(full);
						sReturn = '<div><a href="javascript:Page.onModifyRecord('+full.id+')" class="btn btn-warning btn-sm">【修改记录】 </a> ' +
							'<a href="javascript:Page.onDeleteRecord('+full.id+')" class="btn btn-danger btn-sm">【删除记录】 </a></div>';
						return sReturn;
					},"orderable": false}],
			"aLengthMenu": [[5,10,15,20,25,40,50,-1],[5,10,15,20,25,40,50,"所有记录"]],
			"fnDrawCallback": function(){$(".checkboxes").uniform();$(".group-checkable").uniform();},
			"sAjaxSource": ""+module+"_"+sub+"_servlet_action?action="+action_value+""
		});
		$('.datatable').find('.group-checkable').change(function () {
			var set = jQuery(this).attr("data-set");
			var checked = jQuery(this).is(":checked");
			jQuery(set).each(function () {
				if (checked) {
					$(this).attr("checked", true);
					$(this).parents('tr').addClass("active");
				} else {
					$(this).attr("checked", false);
					$(this).parents('tr').removeClass("active");
				}
			});
			jQuery.uniform.update(set);
		});
		$('.datatable').on('change', 'tbody tr .checkboxes', function () {
			$(this).parents('tr').toggleClass("active");
		});
	};



	var onModifySubmit =function () {
		$('#record_modify_div').modal("hide");
		onModifySubmitDiv();
	};

	var onModifySubmitDiv=function(){
		if(confirm("您确定要修改该记录吗？")){
			var url=module+"_"+sub+"_servlet_action";
			var data={};
			data.action="modify_Weather_record";
			data.id=$('#record_modify_div #id').val();
			data.max_temperature=$('#record_modify_div #max_temperature').val();
			data.min_temperature=$('#record_modify_div #min_temperature').val();
			data.type=$('#record_modify_div #type').val();
			$.post(url,data,function(json){
				if(json.result_code==0){
					alert("已经完成天气信息修改。");
					window.location.reload();
				}
			});
		}
	};

	var onAddSubmit =function () {
		$('#record_add_div').modal("hide");
		var city = document.getElementById("city").value;   //此方法兼容性好
		alert("获取到的city值为："+city);
		GetweatherData(city);
	};

	var onDataTableTab=function(){
		$("#datatable_tab").show();
	};

	var onExportRecord=function(){
		var url=module+"_"+sub+"_servlet_action";
		var data={};
		data.action="export_Weather_Information_record";
		$.post(url,data,function(json){
			if(json.result_code==0){
				console.log(JSON.stringify(json));  //最好在后端再次拦截一下
				$('#record_export_div #download_url').attr("href",json.download_url);
				$('#record_export_div').modal("show");
			}
			else{
				alert("[onExportRecord]与后端交互错误！"+json.result_msg);
			}
		});
	};

	var changeResultDataToChartData = function(list,chartData) {
		//list的元素是: time_interval, total
		//chartData的元素是: date, duration
		if(chartData!=null){
			chartData.length=0; // 这里一定要注意不能用chartData=[]，因为这样写是赋予一个新的空数组，不是原来那个了，
			                    // 并且在这里声明的空数组还是临时变量，不会传播到后面，所以这里会报错。必须这样在原数组上清空
		}
		for (var i = 0; i < list.length; i++) {
			// list[i].time_interval = i;
			var json = {"type": list[i].type.toString(), "number": list[i].number};
			chartData.push(json);
		}
	};

	var changeResultDataToWeatherChartData = function(list,weather_graph_data) {
		//list的元素是: time_interval, total
		//weather_graph_data的元素是: date, duration
		if(weather_graph_data!=null){
			weather_graph_data.length=0; // 这里一定要注意不能用weather_graph_data=[]，因为这样写是赋予一个新的空数组，不是原来那个了，
								// 并且在这里声明的空数组还是临时变量，不会传播到后面，所以这里会报错。必须这样在原数组上清空
		}
		var temp1=list.high;
		var temp2=list.low;
		var temp3=list.fengli;
		sessionStorage.setItem('today_max_temperature',  temp1.substring(3,temp1.length-1));
		sessionStorage.setItem('today_min_temperature',  temp2.substring(3,temp2.length-1));
		sessionStorage.setItem('today_fengli',  temp3.substring(9, temp3.length-4));

		var json1 = {"label":"最高温度", "value":sessionStorage.getItem("today_max_temperature")};
		var json2 = {"label":"最低温度", "value": sessionStorage.getItem("today_min_temperature")};
		var json3 = {"label":"风的等级", "value": sessionStorage.getItem("today_fengli")};
		weather_graph_data.push(json1);
		weather_graph_data.push(json2);
		weather_graph_data.push(json3);
		console.log("构造的画图数据是："+weather_graph_data);
	};

	var initBarChart = function(){
		var bar = new Morris.Bar({
			element: 'bar-chart',
			resize: true,
			data: chartData,
			barColors: ['#00a65a'],
			xkey: 'type',
			// 这样设置可以有多个标签，画出更多图 ykeys: ['number', 'expenses'],
			ykeys: ['number'],
			labels: ['数量'],
			hideHover: 'auto'
		});
	};

			//Page return 开始
	return {
		init: function() {
			initPageControl();
		},
		onDeleteRecord:function(id){
			onDeleteRecord(id);
		},
		onModifyRecord:function(id){
			onModifyRecord(id);
		},
		onViewRecord:function(id){
			onViewRecord(id);
		}
	}
}();//Page
/*================================================================================*/
